package edu.nepu.flink.api.sql;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Date 2024/3/5 21:45
 * @Created by chenshuaijun
 */
public class SelfDefineAggregateFunction {


    public static void main(String[] args) {


        /**
         *
         *  聚合函数的本质就是多进一出:
         *  下面我将演示自定义标量函数的过程，实现一个求和
         */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<WaterSensor> sensorDS = env.fromElements(
                new WaterSensor("s1", 1L, 1),
                new WaterSensor("s1", 2L, 2),
                new WaterSensor("s2", 2L, 2),
                new WaterSensor("s3", 3L, 3),
                new WaterSensor("s3", 4L, 4)
        );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        //TODO 注意这里创建的是一个临时的系统函数
        tableEnv.createTemporaryFunction("aggFunction",MyAggregateFunction.class);

        Table sensorTable = tableEnv.fromDataStream(sensorDS);

        tableEnv.createTemporaryView("sensors",sensorTable);

        tableEnv.sqlQuery("select id,aggFunction(vc) as a from sensors group by id").execute().print();

    }

    public static class MyAggregateFunction extends AggregateFunction<Integer,Integer> {

        @Override
        public Integer getValue(Integer accumulator) {

            return accumulator;
        }

        @Override
        public Integer createAccumulator() {
            return 0;
        }

        public void accumulate(Integer acc, Integer value) {
            acc += value;
        }

        public void merge(Integer acc, Iterable<Integer> it) {
            for (Integer a : it) {
                acc += a;
            }
        }
    }
}
